<template>
  <div class="all">
    <div class="class">
      <div class="class-header">
        <div class="header-left">
          <div class="line"></div>
          <div class="title">日常</div>
          <el-input
            v-model="classSearchInput"
            placeholder="请输入姓名"
            style="width: 150px"
            class="className"
            v-if="role != '3'"
          ></el-input>
          <el-date-picker
            v-model="currentYearMonth"
            type="month"
            placeholder="选择查询时间"
            style="width: 150px"
            value-format="YYYY-MM"
            class="className"
          ></el-date-picker>
          <div style="position: relative">
            <el-button @click="handleSearch" class="search">搜索</el-button>
            <img src="../../assets/images/搜索.png" class="searchImg" alt="" />
          </div>
        </div>
        <div class="header-right">
          <el-button link type="primary" class="addRiBao" @click="handleAddRiBao" v-if="role == '3'"
            >写日报</el-button
          >
        </div>
      </div>
    </div>

    <div class="class-content">
      <el-table :data="tableData" style="width: 100%" @row-click="handleRowClick">
        <el-table-column prop="teacherName" label="姓名" align="center" />
        <el-table-column prop="reportContent" label="报告内容" align="center">
        </el-table-column>

        <el-table-column prop="reportDate" label="日期" align="center" />
      </el-table>
      <div class="page">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :current-page="currentPage"
          :page-size="pageSize"
          @current-change="handleCurrentPageChange"
        />
        <div> 
            每页
            <el-input-number
              v-model="pageSize"
              :min="1"
              :max="30"
              controls-position="right"
              @change="handleChange"
            />条
        </div>

      </div>
    </div>
    <!-- 新增：写日报模态框 -->
    <el-drawer v-model="writeReportDialogVisible" title="日常信息" size="700" :show-close="false" style="background-color:#F0F8FF">
      <el-form
        :model="RiBaoData"
        :rules="rules"
        ref="formRef"
        label-width="100px"
        hide-required-asterisk
      >
        <el-row>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="RiBaoData.name" disabled />
          </el-form-item>
          <el-form-item label="日期" prop="date">
            <el-date-picker
              v-model="RiBaoData.date"
              type="date"
              placeholder="请选择开始时间"
              style="width: 200px"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item prop="content" label="内容">
            <div style="border: 1px solid #ccc">
              <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
                :mode="mode"
              >
              </Toolbar>
              <Editor
                style="height: 390px; width: 558px; overflow-y: auto"
                v-model="valueHtml"
                :defaultConfig="editorConfig"
                :mode="mode"
                @onCreated="handleCreated"
              />
            </div>
          </el-form-item>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="writeReportDialogVisible = false" class="cancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm" class="confirm">确认</el-button>
      </template>
    </el-drawer>
    <!-- 展示日报模态框 -->
    <el-drawer v-model="dialogVisible" title="日常详情信息" :show-close="false" size="700" style="background-color:#F0F8FF">
      <div class="richang">
        <div class="name">
          <span class="name1">姓名：</span>
          <span class="name2">{{ selectedRow.teacherName }}</span>
        </div>
        <div class="date">
          <span class="date1">日期：</span>
          <span class="date2">{{ selectedRow.reportDate }}</span>
        </div>
        <div class="content">
          <span class="content1">内容：</span>
          <div class="content2" v-html="selectedRow.reportContent1"></div>
        </div>
      </div>
      <template #footer>
        <el-button @click="dialogVisible = false" class="confirm">关闭</el-button>
      </template>
    </el-drawer>
  </div>
</template>
    
  <script setup>
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDay, addDay, getDayInfo } from '../api/Daily'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

//本地存储
const user = JSON.parse(localStorage.getItem('user'))

// 获取角色信息
const role = user.roleId
// 定义当前年月
const currentYearMonth = ref('')
// 表格数据
const tableData = ref([])
// 分页数据
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(7)
// 搜索框输入
const classSearchInput = ref('')

const mode = 'default' // 编辑器模式，'simple' 或 'default'
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
// 内容 HTML
const valueHtml = ref()
const toolbarConfig = {
  excludeKeys: [
    'uploadImage', // 移除图片上传
    'insertImage', // 移除插入图片
    'uploadVideo', // 移除视频上传
    'codeBlock', // 移除代码块
    'blockquote', // 移除引用
    '|', // 移除分隔符
    'group-more-style', // 移除更多样式组
  ],
  toolbarKeys: [
    'fontFamily',
    'bold',
    'italic',
    'underline',
    'through',
    'color',
    'bgColor',
    'clearStyle',
    'justifyLeft',
    'justifyCenter',
    'justifyRight',
    'justifyJustify',
    'bulletedList',
    'numberedList',
    'fontSize',
    'fontFamily',
    'lineHeight',
    'undo',
    'redo',
  ],
}

const editorConfig = {
  placeholder: '请输入内容...',
}
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}



//获取日常数据
function fetchData() {
  let data = {
    pageIndex: currentPage.value,
    pageSize: pageSize.value,
  }
  if (classSearchInput.value) {
    data.search = classSearchInput.value
  }
  if (currentYearMonth.value) {
    data.thisMonth = currentYearMonth.value
  }
  getDay('dailyList', data).then((res) => {
    if (res.code == 200) {
      tableData.value = res.dataset.dailyList
      total.value = res.dataset.pageCount * pageSize.value
    }
  })
}

//个人日报
function getDayInfoData() {
  let data = {
    pageIndex: currentPage.value,
    pageSize: pageSize.value,
    teacherId: user.userId,
  }
  if (currentYearMonth.value) {
    data.thisMonth = currentYearMonth.value
  }
  getDayInfo('dailyList2', data).then((res) => {
    if (res.code == 200) {
      tableData.value = res.dataset.dailyList2
      total.value = res.dataset.pageCount * pageSize.value
    }
  })
}

// 数据获取
onMounted(() => {
  if (role == '3' || role == '5') {
    getDayInfoData()
  } else {
    fetchData()
  }
})

// 处理当前页变化
const handleCurrentPageChange = (value) => {
  currentPage.value = value
  if (role == '3' || role == '5') {
    getDayInfoData()
  } else {
    fetchData()
  }
}

//搜索
const handleSearch = () => {
  currentPage.value = 1
  if (role == '3' || role == '5') {
    getDayInfoData()
  } else {
    fetchData()
  }
}

// 定义模态框显示状态
const dialogVisible = ref(false)
// 定义选中的行数据
const selectedRow = ref({})
// 处理表格行点击事件
const handleRowClick = (row) => {
  selectedRow.value = row
  dialogVisible.value = true
}

// 写日报模态框显示状态
const writeReportDialogVisible = ref(false)
// 日报表单数据
const RiBaoData = ref({
  name: user.userName,
  content: '',
  date: '',
})
// 处理写日报按钮点击事件
const handleAddRiBao = () => {
  if (formRef.value) {
    formRef.value.clearValidate()
  }
  // 清空表单数据
  if (editorRef.value) {
    editorRef.value.clear()
  }
  RiBaoData.value = {
    name: user.userName,
    content: '',
    date: '',
  }
  writeReportDialogVisible.value = true
}
// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  date: [{ required: true, message: '请选择日期', trigger: 'change' }],
  content: [
    {
      validator: (_, __, callback) => {
        if (!valueHtml.value || valueHtml.value.trim() === '<p><br></p>') {
          callback(new Error('请输入报告内容'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
}

// 表单引用
const formRef = ref(null)

//添加日报接口
function addRiBao() {
  let data = {
    teacherId: user.userId,
    reportContent: editorRef.value.getText(),
    reportDate: RiBaoData.value.date,
    teacherName: user.userName,
    reportContent1:valueHtml.value,
  }
  addDay('addDaily', data).then((res) => {
    if (res.code == 200) {
      if (role == '3' || role == '5') {
        getDayInfoData()
      } else {
        fetchData()
      }
    }
  })
}

// 处理提交日报
const handleConfirm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('是否提交日报？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          addRiBao()
          writeReportDialogVisible.value = false
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '取消提交',
          })
        })
    }
  })
}

function handleChange() {
  currentPage.value = 1;
  if (role == '3' || role == '5') {
    getDayInfoData()
  } else {
    fetchData()
  }
}


</script>
    
  <style scoped>
.class {
  width: 90%;
  height: 10%;
  margin-bottom: 20px;
  margin-top: 20px;
}

/* 头部左侧 */
.header-left {
  display: flex;
  align-items: center;
  margin-left: 40px;
}
.line {
  width: 2px;
  height: 20px;
  background-color: #007bff;
}
.title {
  padding-left: 10px;
  font-size: 20px;
  margin-right: 20px;
}
.className {
  margin-right: 10px;
}
.line2 {
  width: 10px;
  height: 2px;
  margin-left: 5px;
  margin-right: 5px;
  background-color: #9b9b9b;
}
:deep(.className .el-input__wrapper){
  border-radius: 12px !important;
}
.search {
  background-color: #0f6ab1;
  color: #fff;
  border: none;
  margin-left: 10px;
  border-radius: 16px;
  padding: 0;
  padding-right: 15px;
  padding-left: 36px;
}
.searchImg {
  position: absolute;
  top: 8px;
  left: 25px;
}
/* 头部右侧 */
.header-right {
  display: flex;
  align-items: center;
  margin-right: 40px;
}
.currentTime {
  font-size: 15px;
  margin-right: 10px;
}
.calendar-icon {
  display: flex;
  align-items: center;
}
.custom-calendar-icon {
  font-size: 20px; /* 可以根据需要调整图标大小 */
}
.addRiBao {
  margin-left: 10px;
  font-size: 15px;
}

/* 表格区域 */
.class-content {
  width: 90%;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

/* 表格数据 */
:deep(.el-table thead th) {
  background-color: #fbfcff !important;
}
:deep(.el-table .cell) {
  color: black;
}
:deep(.details1) {
  margin-left: 55px;
}
/* 报告不能换行 */
:deep(.el-table__body-wrapper .cell) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
/* 分页 */
.page {
  margin-top: 50px;
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;

}
/* 分页背景色 */
:deep(.el-pager .is-active) {
  background-color: #0f6ab1 !important;
}

/* 模态框 */
:deep(.el-overlay .el-overlay-dialog) {
  position: absolute;
}
:deep(.el-overlay) {
  position: absolute;
}
:deep(.el-dialog) {
  padding: 0px;
  width: 800px;
}
:deep(.el-dialog header span) {
  display: inline-block;
  width: 100%;
  background-color: #0f6ab1;
  height: 40px;
  color: white;
  font-size: 15px;
  text-align: center;
  line-height: 40px;
}
:deep(.el-dialog__footer) {
  text-align: center;
  padding-bottom: 20px;
}
:deep(.confirm) {
  color: white;
  margin-left: 50px;
  background-color: #0f6ab1;
}
:deep(.cancel) {
  background-color: #0f6ab1;
  color: white;
}
.richang{
  height: 100%;
}
.name,
.content,
.date {
  color: black;
  font-size: 15px;
  margin-left: 20px;
}
.content {
  height: 85%;
  display: flex;
  margin-top: 20px;
}
.content2 {
  width: 565px;
  height: 100%;
  overflow-y: auto;
  white-space: pre-wrap;
  word-wrap: break-word;
  background-color: white;
}
.date {
  margin-top: 20px;
}
.footer {
  padding-top: 20px;
  padding-bottom: 20px;
  text-align: right;
}
.footer button {
  background-color: #0f6ab1;
  color: white;
  margin-right: 20px;
}
.footer button:hover {
  background-color: #054a80;
  color: white;
}
/* 写日报 */
:deep(.el-textarea__inner) {
  /* 可以换行 */
  white-space: pre-wrap;
  word-wrap: break-word;
}

:deep(.el-drawer header) {
  background-color: #0f6ab1;
  margin-bottom: 0;
  padding-bottom: 20px;
}
:deep(.el-drawer header span) {
  color: white;
}

:deep(.el-drawer__header span) {
  text-align: center;
  color: black;
  font-size: 20px;
}
:deep(.w-e-scroll p) {
  margin: 0;
}
</style>